<template>
  <div>
    <h4>商品管理</h4>
   <MyTable :goodsList="goodsList">
      <template v-slot:header>
          <th scope="col">#</th>
          <th scope="col">商品名称</th>
          <th scope="col">价格</th>
          <th scope="col">标签</th>
          <th scope="col">操作</th>
      </template>
      <template #body="{row,index}">
        <td>{{ index+1 }}</td>
        <td>{{ row.goods_name }}</td>
        <td>￥{{ row.goods_price }}</td>
        <td>
          <!-- @blur 失去焦点调用 -->
          <!-- @keyup.esc 按下ESC键清空输入框 -->
          <input type="text" v-if="row.inputVisible" class="form-control form-control-sm ipt-tag" v-focus v-model="row.inputValue" @blur="onInputConfig(row)" @keyup.enter="onInputConfig(row)" @keyup.esc="row.inputValue=''"/>
          <button v-else class="btn btn-outline-primary rounded-pill" @click="row.inputVisible=true">+Tag</button>
          <span class="btn btn-outline-dark" v-for="item in row.tags" :key="item">
            {{ item }}
          </span>
        </td>
        <td>
          <button type="button" class="btn btn-outline-danger btn-sm" @click="onRemove(row.id)">删除</button>
        </td>
      </template>
   </MyTable>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import MyTable from './components/MyTable.vue'
const goodsList = ref([
  {
    id:1,
    goods_name:'夏季专柜价男士短袖T恤男韩版圆领纯棉POLO衫',
    goods_price:100,
    tags:['舒适','耐穿'],
    inputVisible:false,
    inputValue:''
  },
  {
      id:2,
      goods_name:'冬季休闲男士短袖T恤男韩版圆领纯棉POLO衫',
      goods_price:200,
      tags:['保暖','轻便'],
      inputVisible:false,
      inputValue:''
  }
])
const vFocus = (el)=>{
  // 获取焦点
  el.focus()
}
function onRemove(id){
  goodsList.value = goodsList.value.filter(item=>item.id !== id)
}
function onInputConfig(row){
  const val = row.inputValue
  console.log(val);
  row.inputValue = ''
  row.inputVisible = false
  // console.log(row.tags);
  // 找到了tag或者为空
  if(!val || row.tags.indexOf(val) !== -1){
    return;
  }
  row.tags.push(val)
}
</script>

<style scoped>
th {
  text-align: center;
}
td{
  line-height: 30px;
  text-align: center;
}
.ipt-tag{
  display: inline-block;
  width: 80px;
}
</style>
